<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\web\controller;
use app\common\controller\Api;
use app\common\model\Factor;
use app\common\model\Fenorder;
use app\web\controller\Express;
use think\Db;

/**
 * 挂账人员名单
 * @package app\index\controller
 */
class Charge extends Auth
{
    public $noNeedLogin = [];

    /**
     *获取挂账人员名单列表
     * @return array
     */
    public function lists()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if(empty($getData['page']) || empty($getData['limit'])){
                $this->result('缺少参数', '', 204);
            }
            $sql = Db::name('qt_charge')
                ->field('c.*,u.real_name,cc.company_name')
                ->alias('c')
                ->leftJoin('qt_users u','u.id = c.user_id')
                ->leftJoin('qt_charge_company cc','c.company_id = cc.id')
                ->where(['c.store_id' => $userInfo['store_id']]);
            //姓名查询
            if(!empty($getData['name'])){
                $sql->where('c.name',$getData['name']);
            }
            //手机号查询
            if(isset($getData['phone']) && !empty($getData['phone'])){
                $sql->whereLike('c.phone','%'.$getData['phone'].'%');
            }
            //公司查询
            if(isset($getData['company_id']) && !empty($getData['company_id'])){
                $sql->where('c.company_id',$getData['company_id']);
            }
            $data = $sql->order('c.id desc')->paginate($getData['limit']);
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 添加挂账单位
     */
    public function add(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['company_name']) || empty($getData['company_address'])){
                $this->result('缺少参数', '', 204);
            }
            if(!isset($getData['content'])){
                $this->result('缺少备注字段', '', 204);
            }
            $insert = [
                'company_name'=>$getData['company_name'],
                'company_address'=>$getData['company_address'],
                'content'=>$getData['content'],
                'user_id'=>$this->userInfo['id'],
                'store_id'=>$this->userInfo['store_id'],
                'create_time'=>time(),
            ];
            $insert = Db::name('qt_charge_company')->insert($insert);
            if($insert){
                $this->result('添加成功', '', 200);
            }
            $this->result('添加失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 编辑人员名单
     */
    public function save(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['name']) || empty($getData['phone'])  || empty($getData['company_id'])){
                $this->result('缺少参数', '', 204);
            }
            if(!isset($getData['content'])){
                $this->result('缺少备注字段', '', 204);
            }
            unset($getData['create_time']);
            $getData['update_time'] = time();
            $update= Db::name('qt_charge')->where('id',$getData['id'])->update($getData);
            if($update !== false){
                $this->result('修改成功', '', 200);
            }
            $this->result('修改失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 编辑人员名单
     */
    public function edit(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $data= Db::name('qt_charge')->field('id,name,phone,company_id,content')->where('id',$getData['id'])->find();
            $data['company_name'] = Db::name('qt_charge_company')->where('id',$data['company_id'])->value('company_name');
            $this->result('保存成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 删除挂账单位
     */
    public function delete(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $data= Db::name('qt_charge_company')->where('id',$getData['id'])->delete();
            $this->result('删除成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 挂账详情
     */
    public function detail(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['page']) || empty($getData['limit']) || empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $checkOutId = Db::name('qt_charge')->where('id',$getData['id'])->value('check_out_id');
            $orderId = Db::name('qt_check_out')->where('id',$checkOutId)->value('project_order');
            $data= Db::name('qt_order')
                ->field('o.id,o.order_no,o.total_price,o.content,u.real_name,o.room_id,o.hand_card_id,o.charge_time')
                ->alias('o')
                ->leftJoin('qt_users u','u.id = o.cashier_id')
                ->where('o.id',$orderId)
                ->paginate($getData['limit'])->each(function ($item){
                    $item['room_name'] = Db::name('qt_room')->where('id',$item['room_id'])->value('name');
                    $item['hand_name'] = Db::name('qt_hand_card')->where('id',$item['hand_card_id'])->value('name');
                    //获取技师
                    $engineerID = Db::name('qt_order_project')
                        ->where('is_delete',2)->where('order_id',$item['id'])->column('engineer_id');
                    $engineerRes = Db::name('qt_users')->whereIn('id',$engineerID)->column('work_number');
                    $item['engineer_number'] = implode(',',$engineerRes);
                    return $item;
                });
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 撤销单个详情挂账
     */
    public function close_detail(){
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $userInfo = $this->userInfo;
            if (empty($post['check_out_id'])) {
                $this->result('ID不能为空', '', 204);
            }
            //结账单中的房间id
            $check_out_data = Db::name('qt_check_out')
                ->where('id', $post['check_out_id'])
                ->where('store_id', $this->userInfo['store_id'])
                ->find();
            dump($check_out_data);die;
            if (empty($check_out_data)) {
                $this->result('没有找到对应ID的数据', '', 204);
            }
            $room_ids = Db::name('qt_order')->whereIn('id', explode(',', $check_out_data['project_order']))
                ->where('store_id', $this->userInfo['store_id'])->column('room_id');
            $room_ids = array_unique($room_ids);

            $data = [];
            if (!empty($post['is_revoke'])) {
                $data['is_revoke'] = $post['is_revoke'];
                $data['pay_status'] = 2;
                $data['revoke_person'] = $userInfo['id'];
                $data['revoke_time'] = time();

                $store_info = Db::name('qt_store')->where(['id' => $userInfo['store_id']])->find();
                if (!empty($store_info['cancel_order_block']) && !empty($check_out_data['cashier_time'])) {
                    if ($check_out_data['cashier_time'] < (time() - $store_info['cancel_order_block'] * 3600)) {
                        $this->result('只能撤销' . $store_info['cancel_order_block'] . ' 小时的订单', '', 204);
                    }
                }

                //$order_queue_data = Db::name('qt_order_queue')->whereIn('id',$room_ids)->find();
                //if (empty($order_queue_data)) {
                //    $this->result('技师已经下钟不能撤销！', '', 204);
                //}
                if (!empty($room_ids)) {
                    //空闲可撤销
                    $is_empty_room = Db::name('qt_room')->whereIn('id', $room_ids)->where('status_id', '<>', 1)->find();
                    if (!empty($is_empty_room)) {//如果房间不是空闲则判断房间是否支付，不是未支付的，不能撤销
                        $order_data = Db::name('qt_order')->whereIn('id', explode(',', $check_out_data['project_order']))->where('pay_status', '<>', 1)->select();
                        $product_data = Db::name('qt_product_order')->whereIn('id', explode(',', $check_out_data['goods_order']))->where('pay_status', '<>', 1)->select();
                        if (!empty($order_data) || !empty($product_data)) {
                            $this->result('订单已支付或者挂账不能撤销！', '', 204);
                        }
                    }
                }
            }

            if (!empty($post['pay_content'])) {
                $data['pay_content'] = $post['pay_content'];
            }
            if (!empty($post['revoke_remarks'])) {
                $data['revoke_remarks'] = $post['revoke_remarks'];
            }

            Db::startTrans();

            try {
                Db::name('qt_check_out')->where('id', $post['check_out_id'])->where('store_id', $this->userInfo['store_id'])->update($data);
                //修改项目订单状态
                Db::name('qt_order')->whereIn('id', explode(',', $check_out_data['project_order']))->update(['pay_status' => 1]);
                Db::name('qt_order_project')->whereIn('order_id', explode(',', $check_out_data['project_order']))->update(['pay_status' => 0]);

                //修改商品订单状态
                Db::name('qt_product_order')->whereIn('id', explode(',', $check_out_data['goods_order']))->update(['pay_status' => 1, 'order_status' => 0]);
                Db::name('qt_product_order_item')->whereIn('order_id', explode(',', $check_out_data['goods_order']))->update(['pay_status' => 0]);

                //更新房间状态可支付
                Db::name('qt_room')->whereIn('id', $room_ids)->update(['status_id' => 10]);
                //删除挂账记录
                Db::name('qt_charge_item')->whereIn('check_out_id', $post['check_out_id'])->delete();
                $chargeId =  Db::name('qt_charge_item')->where('check_out_id', $post['check_out_id'])->value('charge_id');
                //更新挂账金额
                Db::name('qt_charge')->whereIn('id', $chargeId)->setDec('total_price',$check_out_data['total_money']);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->result('请求错误' . $e->getMessage(), '', 204);
            }

            $this->result('修改成功', '', 200);
        }

        $this->result('请求错误', $data, 204);
    }


    /**
     * 补打单个详情挂账
     */
    public function pay_detail(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $update = Db::name('qt_order')->where('id',$getData['id'])->update(['pay_status'=>'2','pay_time'=>time()]);
            if($update !== false){
                $this->result('补打成功', '', 200);
            }
            $this->result('补打失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 挂账订单项目内容记录
     */
    public function order_project_detail(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['check_out_id']) || empty($getData['limit'])){
                $this->result('缺少参数', '', 204);
            }
            $projectItemId = Db::name('qt_check_out_item')->where(['check_out_id'=>$getData['check_out_id'],'link_type'=>'1'])->column('link_order_id');
            $orderProject = Db::name('qt_order_project')
                ->field('op.id,r.name as room_name,h.name as hand_name,u.work_number,op.order_type,op.created_time,op.price,op.payment_price,op.name as project_name')
                ->alias('op')
                ->leftJoin('qt_room r','r.id = op.room_id')
                ->leftJoin('qt_hand_card h','h.id = op.hand_card_id')
                ->leftJoin('qt_users u','u.id = op.engineer_id')
                ->whereIn('op.id',$projectItemId)
                ->where('op.is_delete',2)
                ->paginate($getData['limit']);
            $this->result('查询成功', $orderProject, 200);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 挂账订单商品记录
     */
    public function order_goods_detail(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['check_out_id'])){
                $this->result('缺少参数', '', 204);
            }
            $orderId = Db::name('qt_check_out_item')->where(['check_out_id'=>$getData['check_out_id'],'link_type'=>'2'])->column('link_order_id');
            $goodsRes = Db::name('qt_product_order_item')
                ->field('id,goods_name,goods_num,goods_price,payment_price,create_time,goods_total_price')
                ->whereIn('id',$orderId)
                ->paginate($getData['limit']);
            $this->result('查询成功', $goodsRes, 200);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 删除挂账订单
     */
    public function delete_order(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_charge')->where('id',$getData['id'])->find();
            $chargeData = Db::name('qt_charge_item')->where(['charge_id'=>$getData['id']])->find();
            if(!empty($chargeData)){
                $this->result('有挂账记录无法删除','',204);
            }
            if($find['total_price'] != $find['payment_price']){
                $this->result('有未结清的金额无法删除','',204);
            }
            try{
                Db::startTrans();
                //删除挂账订单
                Db::name('qt_charge')->where(['id'=>$getData['id']])->delete();
                //更新订单状态
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('删除失败','',204);
            }
            $this->result('删除成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 挂账订单明细表
     * @throws \think\db\exception\DbException
     * @throws \think\exception\DbException
     */
    public function total_lists()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $userInfo = $this->userInfo;
            $sql = Db::name('qt_charge')
                ->field('c.id,c.name,c.phone,cc.company_name,c.total_price,c.payment_price,c.create_time')
                ->alias('c')
                ->leftJoin('qt_charge_company cc','c.company_id = cc.id')
                ->where(['c.store_id' => $userInfo['store_id']])
                ->group('c.company_id')
                ->order('c.id desc');
            //姓名筛选
            if(isset($getData['name']) && !empty($getData['name'])){
                $sql->whereLike('c.name','%'.$getData['name'].'%');
            }
            //挂账单位
            if(isset($getData['company_name']) && !empty($getData['company_name'])){
                $sql->whereLike('cc.company_name','%'.$getData['company_name'].'%');
            }
            //手机号
            if(isset($getData['phone']) && !empty($getData['phone'])){
                $sql->where('c.phone',$getData['phone']);
            }
            //收款人ID
            if(isset($getData['user_id']) && !empty($getData['user_id'])){
                $sql->where('c.user_id',$getData['user_id']);
            }
            //时间
            if(isset($getData['start_time']) && !empty($getData['start_time'])){
                $startTime = strtotime($getData['start_time']);
                $endTime = strtotime($getData['end_time']);
                $sql->whereBetweenTime('c.create_time',$startTime,$endTime);
            }
            $data = $sql->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 挂账人员挂账列表
     * @throws \think\db\exception\DbException
     * @throws \think\exception\DbException
     */
    public function user_lists()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['page']) || empty($getData['limit'])){
                $this->result('缺少参数', '', 204);
            }
            $userInfo = $this->userInfo;
            $sql = Db::name('qt_charge_item')
                ->field('ci.id ,c.name,c.phone,cc.company_name,c.payment_price,c.create_time,ci.user_id,ci.check_out_id,ci.content')
                ->alias('ci')
                ->leftJoin('qt_charge c','ci.charge_id = c.id')
                ->leftJoin('qt_charge_company cc','c.company_id = cc.id')
                ->where(['c.store_id' => $userInfo['store_id']])
                ->order('ci.id desc');
            //姓名筛选
            if(isset($getData['name']) && !empty($getData['name'])){
                $sql->whereLike('c.name','%'.$getData['name'].'%');
            }
            //ID筛选
            if(isset($getData['id']) && !empty($getData['id'])){
                $sql->where('ci.charge_id',$getData['id']);
            }
            //挂账单位
            if(isset($getData['company_name']) && !empty($getData['company_name'])){
                $sql->whereLike('cc.company_name','%'.$getData['company_name'].'%');
            }
            //手机号
            if(isset($getData['phone']) && !empty($getData['phone'])){
                $sql->where('c.phone',$getData['phone']);
            }
            //收款人ID
            if(isset($getData['user_id']) && !empty($getData['user_id'])){
                $sql->where('c.user_id',$getData['user_id']);
            }
            //时间
            if(isset($getData['start_time']) && !empty($getData['start_time'])){
                $startTime = strtotime($getData['start_time']);
                $endTime = strtotime($getData['end_time']);
                $sql->whereBetweenTime('c.create_time',$startTime,$endTime);
            }
            $data = $sql->paginate($getData['limit'])->each(function ($item){
                $item['user_name'] = Db::name('qt_users')->where(['id'=>$item['user_id']])->value('real_name');
                $checkOut = Db::name('qt_check_out')->where(['id'=>$item['check_out_id']])->find();
                $item['check_out_order'] = $checkOut['order_no'];
                $item['room_name'] = Db::name('qt_room')->where(['id'=>$checkOut['room_id']])->value('name');
                $engineerIds = explode(',',$checkOut['engineer_ids']);
                $engineerName = Db::name('qt_users')->whereIn('id',$engineerIds)->column('work_number');
                $item['engineer_name'] = implode(',',$engineerName);
                $item['total_price'] = Db::name('qt_check_out')->where(['id'=>$item['check_out_id']])->value('total_money');
                return $item;
            });
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }



}
